package com.java.main.service.user.impl;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.java.main.constant.Errors;
import com.java.main.controller.user.UserEntryInput;
import com.java.main.controller.user.UserInfoInput;
import com.java.main.controller.user.UserInput;
import com.java.main.controller.user.UserOutput;
import com.java.main.domain.KbmContent;
import com.java.main.domain.user.UserDO;
import com.java.main.domain.user.UserEntryDO;
import com.java.main.domain.user.UserEntryRepository;
import com.java.main.exception.HiBabyGlobalException;
import com.java.main.service.SysBaseServiceImpl;
import com.java.main.service.user.UserService;
import com.java.main.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl extends SysBaseServiceImpl<UserDO, Integer> implements UserService {
	@Value("${encrypt_algorithm}")
	private String encryptAlgorithm;
	private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	@PersistenceContext
	EntityManager entityManager;
	@Autowired
	private UserEntryRepository userEntryRepository;

	@Override
	@Transactional
	public void saveUser(UserDO userDO) {
		// TODO Auto-generated method stub
		String password = StringUtils.encrypt("kbm12345", encryptAlgorithm);
		userDO.setPassword(password);
		userDO.setCategoryId(1);
		userDO.setState(1);
//		String str = serialService.modifyEmpSerial(userDO.getKbmContent());
		entityManager.persist(userDO);
		List<UserEntryDO> list1 = userDO.getEntrys();
		for (UserEntryDO userEntryDO : list1) {
			userEntryDO.setUserId(userDO.getId());
			userEntryDO.setStatus(0);
			userEntryDO.setType(0);
//			userEntryDO.setIdentifier(str);
			entityManager.persist(userEntryDO);

		}
		entityManager.flush();

	}
	@Override
	@Transactional
	public UserDO createUser(String mobile,String userAccount,String password) {
		UserDO userDO = new UserDO();
		userDO.setMobile(mobile);
		userDO.setUserAccount(userAccount);
		String password_md5 = StringUtils.encrypt(password, encryptAlgorithm);
		userDO.setPassword(password_md5);
		entityManager.persist(userDO);
		entityManager.flush();
		return userDO;
	}


	@Override
	@Transactional
	public void modifyUser(UserDO userDO) {
		// TODO Auto-generated method stub
		UserDO do1 = entityManager.find(UserDO.class, userDO.getId());
		do1.setMobile(userDO.getMobile());
		do1.setName(userDO.getName());
		do1.setImg(userDO.getImg());
		do1.setSex(userDO.getSex());
		do1.setMemo(userDO.getMemo());
		do1.setGmt_entry(userDO.getGmt_entry());
		do1.setKbmContent(userDO.getKbmContent());
		if (!StringUtils.isBlank(userDO.getPassword())) {
			String passworld = StringUtils.encrypt(userDO.getPassword(), encryptAlgorithm);
			do1.setPassword(passworld);
		}
		List<UserEntryDO> list1 = userDO.getEntrys();
		for (UserEntryDO userEntryDO : list1) {
			UserEntryDO do2 = entityManager.find(UserEntryDO.class, userEntryDO.getId());
			do2.setUserId(userDO.getId());
			do2.setKbmContent(userDO.getKbmContent());
			do2.setEndemicId(userDO.getKbmContent().getEndemicId());
			do2.setContact(userEntryDO.getContact());
			do2.setDeptId(userEntryDO.getDeptId());
			do2.setEmail(userEntryDO.getEmail());
			do2.setExtension(userEntryDO.getExtension());
			do2.setIdentifier(userEntryDO.getIdentifier());
			do2.setLeaderId(userEntryDO.getLeaderId());
			do2.setPositionId(userEntryDO.getPositionId());
			entityManager.merge(do2);
			entityManager.flush();
		}
		entityManager.merge(do1);
		entityManager.flush();
	}

	@Override
	@Transactional
	public void forbiddenUser(Integer id, KbmContent kbmContent) {
		// TODO Auto-generated method stub
		UserDO do1 = entityManager.find(UserDO.class, id);
		UserEntryDO userEntryDO = userEntryRepository.findByUserIdAndEndemicIdAndTypeAndSoftDelete(do1.getId(),
				kbmContent.getEndemicId(), 0, 0);
		if (userEntryDO == null) {
			throw new HiBabyGlobalException(Errors.NOT_FOUND_USER);
		}
		userEntryDO.setStatus(1);
		userEntryDO.setKbmContent(kbmContent);
		entityManager.merge(userEntryDO);
		entityManager.flush();
	}

	@Override
	public UserDO findByMobile(String mobile) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("mobile", mobile);
		return findOne(param);
	}

	@Override
	public UserDO findByUserAccount(String userAccount) {
		if (StringUtils.isBlank(userAccount)) {
			return null;
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("userAccount", userAccount);
		return findOne(param);
	}

	@Override
	public UserDO findById(Integer id) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("id", id);
		return findOne(param);
	}

	@Override
	public UserDO findUserListById(UserInfoInput input, KbmContent kbmContent) {
		// TODO Auto-generated method stub
		UserDO do1 = entityManager.find(UserDO.class, input.getUserId());
		StringBuffer sql1 = new StringBuffer();
		sql1.append(
				"select a.id id,a.create_id create_id,a.create_time create_time,a.endemic_id endemic_id,a.modifiy_id modifiy_id,a.modify_time modify_time,a.soft_delete soft_delete"
						+ " ,a.contact contact,a.dept_id dept_id,a.email email,a.extension extension,a.leader_id leader_id,a.position_id position_id,a.type type,"
						+ " a.user_id user_id,a.identifier identifier, b.name leader_name,a.status status from user_entry a left join user b on a.leader_id=b.id where a.soft_delete=0");
		sql1.append(" and a.endemic_id=" + input.getEndemicId());
		sql1.append(" and user_id=" + do1.getId() + " order by type desc");
		List<UserEntryDO> list1 = entityManager.createNativeQuery(sql1.toString(), UserEntryDO.class).getResultList();
		for (UserEntryDO userEntryDO : list1) {
			StringBuffer sql2 = new StringBuffer();
			sql2.append("select * from user_role where soft_delete=0 and user_id=" + do1.getId() + " and user_entry_id="
					+ userEntryDO.getId());
//			List<UserRoleDO> list2 = entityManager.createNativeQuery(sql2.toString(), UserRoleDO.class).getResultList();
//			userEntryDO.setRoles(list2);
		}
		do1.setEntrys(list1);
		return do1;
	}

	@Override
	@Transactional
	public void saveUserEntry(UserEntryDO userEntryDO) {
		// TODO Auto-generated method stub
		userEntryDO.setType(1);
		userEntryDO.setStatus(0);
//		String str = serialService.modifyEmpSerial(userEntryDO.getKbmContent());
//		userEntryDO.setIdentifier(str);
		entityManager.persist(userEntryDO);
//		for (UserRoleDO userRoleDO : userEntryDO.getRoles()) {
//			UserRoleDO role = userRoleRepository.findByUserIdAndRoleIdAndSoftDelete(userEntryDO.getUserId(),
//					userRoleDO.getRoleId(), 0);
//			if (role != null) {
//				throw new HiBabyGlobalException(Errors.DATA_ROLE_REPEAT);
//			}
//			userRoleDO.setUserId(userEntryDO.getUserId());
//			userRoleDO.setKbmContent(userEntryDO.getKbmContent());
//			userRoleDO.setUserEntryId(userEntryDO.getId());
//			entityManager.persist(userRoleDO);
//		}
		entityManager.flush();
	}

	@Override
	@Transactional
	public void deleteUserEntry(Integer entryId, KbmContent kbmContent) {
		// TODO Auto-generated method stub
		UserEntryDO entryDO = entityManager.find(UserEntryDO.class, entryId);
		entryDO.setSoftDelete(1);
		entryDO.setKbmContent(kbmContent);
		entityManager.merge(entryDO);
		entityManager.flush();
//		List<UserRoleDO> rolelist = userRoleRepository.findByUserIdAndUserEntryIdAndSoftDelete(entryDO.getUserId(),
//				entryDO.getId(), 0);
//		for (UserRoleDO userRoleDO : rolelist) {
//			UserRoleDO role = entityManager.find(UserRoleDO.class, userRoleDO.getId());
//			kbmContent.setDel(1);
//			role.setKbmContent(kbmContent);
//			entityManager.remove(role);
//			entityManager.flush();
//		}
	}

	@Override
	public List<UserOutput> findUserList(UserInput input) {
		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer();
		sql.append(
				"SELECT distinct a.id id,b.identifier identifier,a.name name,b.status status, b.position_id position_id,b.dept_id dept_id,b.endemic_id endemic_id, ");
		sql.append("(SELECT  GROUP_CONCAT(role_id) roleid   FROM user_role   WHERE user_id = a.id and soft_delete=0");
		if (input.getRoleId() != null) {
			sql.append("AND role_id=" + input.getRoleId());
		}
		if (input.getTissueProperty() == 1 || input.getTissueProperty() == 2) {
			sql.append(" AND endemic_id =" + input.getNodeid());
		} else if (input.getTissueProperty() == 3) {
//			DepartmentDO dept = departmentRepository.findByIdAndSoftDelete(input.getNodeid(), 0);
//			sql.append(" AND endemic_id =" + dept.getParentId());
		}
		sql.append(" GROUP BY user_id) role_id ");
		sql.append(
				" FROM USER a,  user_entry b,user_role c   WHERE a.soft_delete=0 and b.soft_delete=0 and c.soft_delete=0 and  a.id = b.user_id and b.id=c.user_entry_id AND a.id=c.user_id  AND b.type = 0");
		if (input.getTissueProperty() == 1 || input.getTissueProperty() == 2) {
			sql.append(" AND b.endemic_id =" + input.getNodeid());
		} else if (input.getTissueProperty() == 3) {
			sql.append(" AND b.dept_id =" + input.getNodeid());
		}
		if (!StringUtils.isBlank(input.getName())) {
			sql.append(" AND a.name like '%" + input.getName() + "%'");
		}
		if (input.getStatus() != null) {
			sql.append(" AND b.status=" + input.getStatus());
		}
		if (input.getRoleId() != null) {
			sql.append(" AND c.role_id=" + input.getRoleId());
		}
		sql.append(" order by a.id desc");
		List<UserOutput> list = entityManager.createNativeQuery(sql.toString(), UserOutput.class).getResultList();
		return list;
	}

	@Override
	public UserDO findUserInfoById(Integer id, KbmContent kbmContent) {
		// TODO Auto-generated method stub
		UserDO do1 = entityManager.find(UserDO.class, id);
		StringBuffer sql1 = new StringBuffer();
		sql1.append(
				"select a.id id,a.create_id create_id,a.create_time create_time,a.endemic_id endemic_id,a.modifiy_id modifiy_id,a.modify_time modify_time,a.soft_delete soft_delete"
						+ " ,a.contact contact,a.dept_id dept_id,a.email email,a.extension extension,a.leader_id leader_id,a.position_id position_id,a.type type,"
						+ " a.user_id user_id,a.identifier identifier, b.name leader_name,a.status status from user_entry a left join user b on a.leader_id=b.id where a.soft_delete=0 and a.endemic_id="
						+ kbmContent.getEndemicId() + " and user_id=" + do1.getId() + " and type=0 order by a.id desc");
		List<UserEntryDO> list1 = entityManager.createNativeQuery(sql1.toString(), UserEntryDO.class).getResultList();
		do1.setEntrys(list1);
		return do1;
	}

	@Override
	@Transactional
	public void updateUserEntry(UserEntryInput input, KbmContent kbmContent) {
		// TODO Auto-generated method stub
		UserEntryDO userEntryDO = entityManager.find(UserEntryDO.class, input.getUserEntryId());
		userEntryDO.setContact(input.getContact());
		userEntryDO.setKbmContent(kbmContent);
		entityManager.merge(userEntryDO);
		entityManager.flush();
	}

	@Override
	@Transactional
	public void updatePassWord(UserDO userDO) {
		// TODO Auto-generated method stub
		UserDO do1 = entityManager.find(UserDO.class, userDO.getId());
		do1.setKbmContent(userDO.getKbmContent());
		do1.setPassword(userDO.getPassword());
		entityManager.merge(do1);
		entityManager.flush();
	}

	@Override
	public UserDO findLoginUserListById(Integer currentUserId, KbmContent kbmContent) {
		// TODO Auto-generated method stub
		UserDO do1 = entityManager.find(UserDO.class, currentUserId);
		StringBuffer sql1 = new StringBuffer();
		sql1.append(
				"select a.id id,a.create_id create_id,a.create_time create_time,a.endemic_id endemic_id,a.modifiy_id modifiy_id,a.modify_time modify_time,a.soft_delete soft_delete"
						+ " ,a.contact contact,a.dept_id dept_id,a.email email,a.extension extension,a.leader_id leader_id,a.position_id position_id,a.type type,"
						+ " a.user_id user_id,a.identifier identifier, b.name leader_name,a.status status from user_entry a left join user b on a.leader_id=b.id where a.soft_delete=0 and a.endemic_id="
						+ kbmContent.getEndemicId() + " and user_id=" + do1.getId() + " order by type desc");
		List<UserEntryDO> list1 = entityManager.createNativeQuery(sql1.toString(), UserEntryDO.class).getResultList();
		for (UserEntryDO userEntryDO : list1) {
		}
		do1.setEntrys(list1);
		return do1;
	}

	@Override
	public List<UserDO> findUserListByDept(String deptid, KbmContent content) {
		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer();
		sql.append(
				" select a.* from user a left join user_entry b on a.id=b.user_id where a.soft_delete=0 and b.soft_delete=0 and b.dept_id="
						+ deptid + " and b.endemic_id=" + content.getEndemicId());
		List<UserDO> list = entityManager.createNativeQuery(sql.toString(), UserDO.class).getResultList();
		return list;
	}

	@Override
	public Integer getMessageQuantity(KbmContent kbmContent) {
		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer();
		sql.append("select count(*) from notification_user where user_id=" + kbmContent.getCurrentUserId()
				+ " and read_type=0 and soft_delete=0 ");
		BigInteger singleResult = (BigInteger) entityManager.createNativeQuery(sql.toString()).getSingleResult();
		return singleResult.intValue();
	}

}
